const mongoose = require("mongoose");
const House = mongoose.model("House");
const { log, Resp, validObjectId } = require("../../config/utils");
class HouseCtrl {
	// 菜单列表
	async list(req, res) {
		let { pageNumber = 1, pageCount = 10, area, link, phone, receiveTime, sId, title, yxdjState } = req.query;
		if (parseInt(pageNumber) < 1) pageNumber = 1;
		if (parseInt(pageCount) < 1) pageCount = 10;
		const cond = {};
		if (area) cond["area"] = area;
		if (link) cond["link"] = link;
		if (phone) cond["phone"] = phone;
		if (sId) cond["sId"] = sId;
		if (title) cond["title"] = title;
		// 未开始
		if (yxdjState && yxdjState == "1") {
			cond.yxdjTimeStart = { $gt: new Date().valueOf() };
		}
		// 正在登记
		if (yxdjState && yxdjState == "2") {
			cond.yxdjTimeStart = { $lt: new Date().valueOf() };
			cond.yxdjTimeEnd = { $gt: new Date().valueOf() };
		}
		// 已经结束
		if (yxdjState && yxdjState == "3") {
			cond.yxdjTimeEnd = { $lt: new Date().valueOf() };
		}
		if (receiveTime) {
			cond.receiveTimeStart = { $lt: new Date(receiveTime).valueOf() };
			cond.receiveTimeEnd = { $gt: new Date(receiveTime).valueOf() };
		}
		try {
			let info = await Promise.all([
				House
					.find(cond, { content: 0, __v: 0 })
					.limit(parseInt(pageCount))
					.skip((parseInt(pageNumber) - 1) * pageCount)
					.sort({ yxdjTimeEnd: -1 }),
				House.countDocuments(cond)
			]);
			log("green", info);
			if (info) {
				res.send(new Resp(1, "查询house成功!", {
					list: info[0] || [],
					sum: info[1],
					pageNumber: parseInt(pageNumber),
					pageCount: parseInt(pageCount)
				}));
			} else {
				log("red", `查库结果：${info}`);
				res.send(new Resp(0, "查询house失败!", null));
			}
		} catch (error) {
			log("red", error.stack);
			res.send(new Resp(0, "查询house失败!", null));
		}
	}
	// 菜单列表
	async detail(req, res) {
		let { _id } = req.params;
		if(!_id) return res.send(new Resp(0, "缺少参数!", null));
		if(!validObjectId(_id)) return res.send(new Resp(0, "id格式错误!", null));
		try {
			let house = await House.findOne({_id});
			if (house) {
				res.send(new Resp(1, "查询house成功!", house));
			} else {
				log("red", `查库结果：${house}`);
				res.send(new Resp(0, "查询house失败!", null));
			}
		} catch (error) {
			log("red", error.stack);
			res.send(new Resp(0, "查询house失败!", null));
		}
	}

}

module.exports = new HouseCtrl();